package com.obrempon.credit.market.httptest.interceptor

import com.obrempon.credit.market.utils.aes.ObremponAesUtil
import com.obrempon.credit.market.utils.log.ObremponLogger
import com.obrempon.module.easyhttp.config.IRequestInterceptor
import com.obrempon.module.easyhttp.model.HttpHeaders
import com.obrempon.module.easyhttp.model.HttpParams
import com.obrempon.module.easyhttp.request.HttpRequest
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2025/2/26 16:06
 * @Annotation：通用请求拦截器，包含参数加密，响应解密，注:不需要加解密的接口，api需要单独实现 IRequestInterceptor 接口
 */
class RequestInterceptor: IRequestInterceptor {

    /**
     * 拦截参数
     *
     * @param httpRequest   接口对象
     * @param params        请求参数
     * @param headers       请求头参数
     */
    override fun interceptArguments(httpRequest: HttpRequest<*>, params: HttpParams, headers: HttpHeaders) {
        super.interceptArguments(httpRequest, params, headers)
    }

    /**
     * 拦截请求头
     *
     * @param httpRequest   接口对象
     * @param request       请求头对象
     * @return              返回新的请求头
     */
    override fun interceptRequest(httpRequest: HttpRequest<*>, request: Request): Request {
        return super.interceptRequest(httpRequest, onRequestEncrypt(request))
    }

    /**
     * 拦截器响应头
     *
     * @param httpRequest   接口对象
     * @param response      响应头对象
     * @return              返回新的响应头
     */
    override fun interceptResponse(httpRequest: HttpRequest<*>, response: Response): Response {
        return super.interceptResponse(httpRequest, onResponseDecrypt(response))
    }

    /**
     * 请求参数加密
     */
    private fun onRequestEncrypt(request: Request): Request{
        var newRequest = request
        val oldRequestBody = newRequest.body
        val requestBuffer = Buffer()
        oldRequestBody?.writeTo(requestBuffer)
        val oldBodyStr = requestBuffer.readUtf8()
        requestBuffer.close()
        val mediaType = "text/plain; charset=utf-8".toMediaTypeOrNull()
        val newBodyStr = ObremponAesUtil.encryptDefault(oldBodyStr)
        ObremponLogger.e(">>>>>>>>>intercept>>>>>url>>>>>>${request.url}")
        ObremponLogger.e(">>>>>>>>>intercept>>>>>body>>>>>>$oldBodyStr")
        ObremponLogger.e(">>>>>>>>>intercept>>>>>body>>aes>>>>$newBodyStr")
        val newBody = newBodyStr.toRequestBody(mediaType)
        newRequest = newRequest.newBuilder()
            .header("Content-Type",newBody.contentType().toString())
            .header("Content-Length", "${newBody.contentLength()}")
            .method(newRequest.method, newBody)
            .build()
        return newRequest
    }

    /**
     * 返回值解密
     */
    private fun onResponseDecrypt(response: Response): Response{
        try {
            val responseBody = response.body
            val responseBodyIn = responseBody?.byteStream()
            val mediaType = responseBody?.contentType()

            val reader = BufferedReader(InputStreamReader(responseBodyIn, Charsets.UTF_8))
            val result = reader.readText()
            val resultDp = ObremponAesUtil.decryptDefault(result)
            val body = resultDp.toResponseBody(mediaType)
            return response.newBuilder().body(body).build()

//            val builder = response.newBuilder()
//            val clone = builder.build()
//            //成功 判断是否等于200
//            if (clone.code != 200) {
//                return response
//            }
//            var body = clone.body
//            if (body != null){
//                val mediaType = body.contentType()
//                if (mediaType != null){
//                    val stringBody = body.string()
//                    val result = ObremponAesUtil.decryptDefault(stringBody)
//                    ObremponLogger.i(">>>>>>>>>>>>>>>>>>>mediaType>>>$mediaType")
//                    ObremponLogger.i(">>>>>>>>>>>>>>>>>>>>>>$result")
//                    body = result.toResponseBody(mediaType)
//                    return response.newBuilder().body(body).build()
//                }
//            }
        } catch (e: Exception){
            return response
        }
        return response
    }

}